package com.clouddrive.File;

import com.clouddrive.User;
import com.clouddrive.dao.impl.UserServiceImpl;
import com.clouddrive.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@WebServlet(value="/downloadfile",name="DownloadFile")
public class DownloadFile extends HttpServlet {
    private final UserService userService= new UserServiceImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        Cookie[] cookies =request.getCookies();
        User nowUser = userService.GetUserByCookie(cookies);

        String fs = File.separator;
        String filepath = request.getServletContext().getRealPath("/");
        filepath = filepath.endsWith(fs) ? filepath : filepath + fs;
        filepath += ".." + fs + "upload" + fs + nowUser.getEmail() + fs;

        String filename=request.getParameter("filename");

        if(filename.contains("/")||filename.contains("\\")){
            return;
        }
        File file = new File(filepath + filename + ".Suzuran");
        if(file.exists()&&file.isFile()){
            response.setContentType("application/x-msdownload");
            System.out.println(filename);
            response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(filename, StandardCharsets.UTF_8));
            InputStream inputStream=new FileInputStream(file);
            ServletOutputStream outputStream=response.getOutputStream();
            byte[] data=new byte[1024];
            int len;
            while((len=inputStream.read(data))!=-1){
                outputStream.write(data,0,len);
            }
            outputStream.close();
            inputStream.close();
        }
        else{
            System.out.println("文件不存在");
        }
        response.sendRedirect(request.getContextPath() + "/disc.html");
    }
}
